package softtech.apps.callblocker;


import java.text.SimpleDateFormat;
import java.util.Calendar;
import softtech.apps.utility.ApplicationConstants;
import softtech.apps.utility.FileUtility;
import softtech.apps.callblocker.model.CallBlockedItem;
import softtech.apps.callblocker.model.DatabaseHanler;
import softtech.apps.callblocker.model.SmsBlockedItem;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

@SuppressLint("SimpleDateFormat")
public class ReceiveDateTimeChange extends BroadcastReceiver {
	
	final String TAG = "Receive Date Time Change";

	@Override
	public void onReceive(Context context, Intent intent) {		

		if (intent.getAction().compareTo(Intent.ACTION_BOOT_COMPLETED) == 0) {

			Log.e(TAG, "DemoReceiver.onReceive(ACTION_BOOT_COMPLETED)");

			context.startService(new Intent(context, ServiceDateTimeChange.class));

		} else if (intent.getAction().compareTo(Intent.ACTION_TIME_TICK) == 0){
			if(checkIsActivated(context)){
				return;
			}
			FileUtility futil = new FileUtility();
			int value1 = 0;
			int value2 = 0;
			int currentvalue = 0;
			// get old value
			try{
				String valuestring1 = futil.getContentFileFromSdcard(ApplicationConstants.PATH_FOLDER_LICENSE, ApplicationConstants.FILE_LICENSE_NAME);
				
				value1 = Integer.parseInt(valuestring1.trim());
			}catch(Exception e){
				e.printStackTrace();
			}
			
			try{
				value2 = Integer.parseInt( futil.LoadContentFile(context, ApplicationConstants.FILE_LICENSE_NAME).trim() );
			}catch(Exception e){
				e.printStackTrace();
			}
			
			currentvalue = Math.max(value1, value2);
			
			
			// update value & save content
			
			++currentvalue;
			updateLicenseFile(context , currentvalue);

			
			// block application
			if(currentvalue == ApplicationConstants.MAX_TIME_FREE){
				generateNotification(context , "Please activated application");
			}
			
			// delete call when out of time
			deleteHistoryOutOfDate(context ,getDateLimited(context));
		}else{
			Log.e(TAG, "DateTimeChangeReceive.onReceive(" + intent.getAction() + ")");
		}
		
	}
	
	/**
     * Issues a notification to inform the user that server has sent a message.
     */
    private static void generateNotification(Context context, String message) {
        int icon = R.drawable.ic_launcher;
        long when = System.currentTimeMillis();
        NotificationManager notificationManager = (NotificationManager)
                context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(icon, message, when);
         
        String title = context.getString(R.string.app_name);
         
        Intent notificationIntent = new Intent(context, ActivityDashboard.class);
        // set intent so it does not start a new activity
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent =
                PendingIntent.getActivity(context, 0, notificationIntent, 0);
        notification.setLatestEventInfo(context, title, message, intent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
         
        // Play default notification sound
        notification.defaults |= Notification.DEFAULT_SOUND;
         
        // Vibrate if vibrate is enabled
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        notificationManager.notify(0, notification);     
 
    }
	
    /**
     * init license file if not exist
     * @param context
     */
    private void updateLicenseFile(Context context , int value){
		
		FileUtility futil = new FileUtility();
		//
		// create folder
		//
		FileUtility.createDirIfNotExists(ApplicationConstants.PATH_FOLDER_LICENSE);
		
		futil.saveContentFileToSdCard(String.valueOf(value), ApplicationConstants.PATH_FOLDER_LICENSE, ApplicationConstants.FILE_LICENSE_NAME);
		futil.SaveContentFile(context, ApplicationConstants.FILE_LICENSE_NAME, String.valueOf(value));
		
	}
    
    /**
	 * check if user is activated
	 * @return
	 * true: activated
	 * false: not activate
	 */
	Boolean checkIsActivated(Context context){
		FileUtility futil = new FileUtility();
		
		//
		// check license
		//
		int value1 = 0;
		int value2 = 0;
		int currentvalue = 0;
		// get old value
		try{
			value1 = Integer.parseInt(futil.getContentFileFromSdcard(ApplicationConstants.PATH_FOLDER_LICENSE, ApplicationConstants.FILE_ACTIVATE_NAME).trim());
		}catch(Exception e){
			e.printStackTrace();
		}
		
		try{
			value2 = Integer.parseInt( futil.LoadContentFile(context, ApplicationConstants.FILE_ACTIVATE_NAME).trim() );
		}catch(Exception e){
			e.printStackTrace();
		}
		
		currentvalue = value1 & value2;
		
		if(value1 ==0){
			futil.saveContentFileToSdCard(String.valueOf(currentvalue), ApplicationConstants.PATH_FOLDER_LICENSE, ApplicationConstants.FILE_ACTIVATE_NAME);
			
		}
		
		if(value2 == 0){
			futil.SaveContentFile(context, ApplicationConstants.FILE_ACTIVATE_NAME, String.valueOf(currentvalue));
		}
		
		if(currentvalue == 1){
			return true;
		}
		return false;
	}
    
	/**
	 * delete history call & sms when out of date
	 */
	void deleteHistoryOutOfDate(Context context , int date_limited){
		
		Calendar cal = Calendar.getInstance();
		if(!(cal.get(Calendar.HOUR_OF_DAY) == 0 && cal.get(Calendar.MINUTE) ==0)){
			return;
		}
		String last_out_date = "";
		cal.add(Calendar.DATE, -date_limited );
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		last_out_date = sdf.format(cal.getTime());
		DatabaseHanler db = new DatabaseHanler(context);
		db.deleteCallBlockItem(CallBlockedItem.DATE_TIME + " < ?", new String[]{last_out_date});
		db.deleteSmsBlockItem(SmsBlockedItem.DATE_TIME + " < ?", new String[]{last_out_date});
	}
	
	/**
	 * get limited date of call & sms history
	 * @param context
	 * @return
	 */
	int getDateLimited(Context context){
		FileUtility futil = new FileUtility();
		int limited_date = 30;
		try{
			
			
			limited_date = Integer.parseInt(futil.LoadContentFile(context, ApplicationConstants.FILE_LIMITED));
			
			if(limited_date == 0){
				futil.SaveContentFile(context, ApplicationConstants.FILE_LIMITED, ""+limited_date);
			}
		}catch(Exception e){
			futil.SaveContentFile(context, ApplicationConstants.FILE_LIMITED, ""+ limited_date);
			e.printStackTrace();
		}
		
		
		
		return limited_date;
	}
	
}
